const WebSocket = require('ws');

function wsFuWu() {
	//websocket
	const wss = new WebSocket.Server({
		port: 8080
	});
	
	let dateNow = new Date().getTime();
	let jueSeHaoChi, jueSeHaoYiYong, tongBuWuTi;
	let jiShaXinXi = '';
	
	function chuShiHua() {
		jueSeHaoChi = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
		jueSeHaoYiYong = new Map();
		jiShaXinXi = '';
	}
	chuShiHua();
	
	
	function guangBo() {
		let now = new Date().getTime();
		let shiChang = now - dateNow;
		if (shiChang > 24 * 60 * 60 * 1000) {
			chuShiHua();
			dateNow = now;
		};
	
		wss.clients.forEach(ws => {
			let xinXiArr = [...jueSeHaoYiYong.values()];
			ws.send(JSON.stringify({
				xinXiArr,
				jiShaXinXi,
				shiJian: now
			}))
		})
	
		jueSeHaoYiYong.forEach(value => {
			value.woBeiDaJi = [];
		})
		jiShaXinXi = '';
	}
	
	setInterval(guangBo, 1000 / 60);
	
	wss.on('connection', ws => {
		if (jueSeHaoChi.length > 0) {
	
			let jueSeHao = jueSeHaoChi.shift();
			jueSeHaoYiYong.set(jueSeHao, {
				woBeiDaJi: []
			});
	
			ws.send(JSON.stringify({
				jueSeHao
			}));
	
			ws.jueSeHao = jueSeHao;
	
		} else {
			ws.send(JSON.stringify({
				jueSeHao: '房间已满'
			}));
	
			return;
		}
	
		ws.on('message', message => {
	
			message = JSON.parse(message);
	
			if (message.leiXing == 'jiShaXinXi') {
				jiShaXinXi = message.neiRong;
				return;
			}
	
			let jueSe = jueSeHaoYiYong.get(message.jueSeHao);
			jueSe.jueSeHao = message.jueSeHao;
			jueSe.weiZhi = message.weiZhi;
			jueSe.xuanZhuan = message.xuanZhuan;
			jueSe.niuZhuan = message.niuZhuan;
			jueSe.dongZuo = message.dongZuo;
	
			if (message.woDaJi) {
				let beiDaJi = jueSeHaoYiYong.get(message.woDaJi.jueSeHao);
				message.woDaJi.jueSeHao = message.jueSeHao; //打击者角色号
				beiDaJi.woBeiDaJi.push(message.woDaJi);
			}
	
		})
	
		ws.on('close', () => {
	
			jueSeHaoYiYong.forEach((h, i, a) => {
				if (i === ws.jueSeHao) {
					a.delete(i);
					jueSeHaoChi.push(i);
				}
			})
	
		})
	})
}

module.exports = wsFuWu;
